﻿<template>
    <div class="container">
        <div class="handle-box">
                <el-form ref="form" :model="searchform" label-width="90px" class="flex">
                    <el-form-item label="所属地区：">
                        <el-input v-model="searchform.name" placeholder="请输入地区" class="handle-input mr10" @input="mohu()"></el-input>
                    </el-form-item>
                    <el-form-item label="街道：">
                        <el-input v-model="searchform.streetname" placeholder="请输入街道" class="handle-input mr10" @input="streetnamemohu()"></el-input>
                    </el-form-item>
                    <!-- <el-form-item label="手机号：">
                        <el-input v-model="name" placeholder="请输入手机号" class="handle-input mr10"></el-input>
                    </el-form-item>
                    <el-form-item label="楼号：">
                        <el-input v-model="name" placeholder="请输入楼号" class="handle-input mr10"></el-input>
                    </el-form-item>
                    <el-form-item label="单元号：">
                        <el-input v-model="name" placeholder="请输入单元号" class="handle-input mr10"></el-input>
                    </el-form-item>
                    <el-form-item label="门牌号：">
                        <el-input v-model="name" placeholder="请输入门牌号" class="handle-input mr10"></el-input>
                    </el-form-item> -->
                    <!-- <el-form-item label="日期范围：">
                       <el-date-picker
                            v-model="value1"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
                        </el-date-picker>
                    </el-form-item> -->
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" @click="searchbtn(searchform)">搜索</el-button>
                        <!-- <el-button type="danger" icon="el-icon-circle-close">清空</el-button> -->
                        <el-button type="success" icon="el-icon-circle-plus-outline" @click="addlistdatadiglog()">新增</el-button>
                        <el-button type="primary" @click="exportToExcel()" style="background:#409EFF;border:1px solid #409EFF">导出列表</el-button>
                        <el-button style="padding:0;border:0">
                             <el-upload
                            action="/上传文件的接口"
                            :on-change="onChange"
                            :auto-upload="false"
                            :show-file-list="false"
                            accept=".xls, .xlsx"  class="upload">
                        <el-button type="warning" icon="el-icon-folder-add" style="width:97px;height:33px">导入列表</el-button>
                        <!-- <el-button type="warning" icon="el-icon-folder-add" style="width:97px;height:33px">导出列表</el-button> -->
                    </el-upload>
                        </el-button>
                    </el-form-item>
                    
                </el-form>
            </div>
            <el-table
                :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)"
            >
                <el-table-column prop="STREET_ID" label="ID" width="55" align="center"></el-table-column>
                <!-- <el-table-column prop="name" label="姓名"></el-table-column> -->
                <!-- <el-table-column prop="phone" label="手机号"></el-table-column> -->
                <el-table-column prop="REGION_NAME" label="所属地区"></el-table-column>
                <el-table-column prop="STREET_NAME" label="街道"></el-table-column>
                <el-table-column prop="ADDRESS" label="地址"></el-table-column>
                 <el-table-column prop="CONTACTS" label="联系人"></el-table-column>
                 <el-table-column prop="TELEPHONE" label="联系人电话"></el-table-column>
                 <!-- <el-table-column prop="CREATETIME" label="创建时间"></el-table-column> -->
                <!-- <el-table-column prop="unit" label="单元"></el-table-column>
                <el-table-column prop="housenumber" label="门牌号"></el-table-column>
                <el-table-column prop="cardnumber" label="卡号"></el-table-column> -->
                <!-- <el-table-column prop="registrationdate" label="注册日期"></el-table-column> -->
                <!-- <el-table-column prop="state" label="状态"></el-table-column> -->
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button> |
                        <el-button
                            type="text"
                            @click="handleDelete(scope.$index, scope.row)" style="color:red"
                        >删除</el-button> |
                        <el-button
                            type="text"
                            @click="handle(scope.$index, scope.row)" style="color:#2A47BD"
                        >积分管理</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, sizes, prev, pager, next, jumper"
                    :current-page="currentPage"  
                    :page-size="pageSize"
                    :total="tableData.length"
                    @size-change="handleSizeChange"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
            <!-- 编辑弹出框 -->
            <el-dialog v-dialogDrag title="编辑街道" :visible.sync="editVisible" width="50%">
                <el-form ref="form" :model="editform" label-width="70px" class="display">
                    <el-form-item label="ID：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="editform.STREET_ID"></el-input>
                    </el-form-item>
                    <el-form-item label="所属地区：" :label-width="labelwidth" class="wid50">
                         <el-select v-model="editform.REGION_ID" placeholder="请选择">
                          <el-option v-for="item in options" :key='item.REGION_ID' :label="item.REGION_NAME" :value="item.REGION_ID">
                          </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="街道：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="editform.STREET_NAME"></el-input>
                    </el-form-item>
                    <el-form-item label="地址：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="editform.ADDRESS"></el-input>
                    </el-form-item>
                    <el-form-item label="经度：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="editform.LONGITUDE"></el-input>
                    </el-form-item>
                    <el-form-item label="纬度：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="editform.LATITUDE"></el-input>
                    </el-form-item>
                    <el-form-item label="联系人：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="editform.CONTACTS"></el-input>
                    </el-form-item>
                    <el-form-item label="联系人电话：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="editform.TELEPHONE"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveEdit">确 定</el-button>
                </span>
            </el-dialog>
            <!-- 新增弹出框 -->
            <el-dialog v-dialogDrag title="新增街道"  :visible.sync="addeditVisible" width="50%">
                <el-form ref="addform" :model="addform" label-width="70px" class="display" :rules="rules">
                    <!-- <el-form-item label="ID：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="addform.id"></el-input>
                    </el-form-item> -->
                    <el-form-item label="所属地区：" :label-width="labelwidth" class="wid50" prop="REGION_ID">
                         <el-select v-model="addform.REGION_ID" placeholder="请选择" @change="getid()">
                          <el-option v-for="item in options" :key='item.REGION_ID' :label="item.REGION_NAME" :value="item.REGION_ID">
                          </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="街道：" :label-width="labelwidth" class="wid50" prop="streetname">
                        <el-input v-model="addform.streetname"></el-input>
                    </el-form-item>
                    <el-form-item label="地址：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="addform.address"></el-input>
                    </el-form-item>
                    <el-form-item label="经度：" :label-width="labelwidth" class="wid50" prop="LONGITUDE">
                        <el-input v-model="addform.LONGITUDE"></el-input>
                    </el-form-item>
                    <el-form-item label="纬度：" :label-width="labelwidth" class="wid50" prop="LATITUDE">
                        <el-input v-model="addform.LATITUDE"></el-input>
                    </el-form-item>
                    <el-form-item label="联系人：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="addform.contacts"></el-input>
                    </el-form-item>
                    <el-form-item label="联系人电话：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="addform.telephone" oninput = "value=value.replace(/[^\d]/g,'')" maxlength="11"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="resetForm('addform')">取 消</el-button>
                    <el-button type="primary" @click="submitForm('addform')">确 定</el-button>
                </span>
            </el-dialog>
        </div>
</template>
<script>
import '../../assets/css/common.css'

export default {
    data(){
        return{
            rules: {
                REGION_ID: [
            { required: true, message: '请选择新增街道所属地区', trigger: 'blur' },
            // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'change' }
          ],
          streetname: [
            { required: true, message: '请输入新增街道的名称', trigger: 'blur' }
          ],
          LONGITUDE: [
            { required: true, message: '请输入真实经纬度', trigger: 'blur' }
          ],
          LATITUDE: [
            { required: true, message: '请输入真实经纬度', trigger: 'blur' }
          ]},
          
              currentPage:1, //初始页
                pagesize:10,    //    每页的数据
                userList: [],
                searchform:{
                    name:'',
                    streetname:''
                },
                editform:{

                },
                value1: '',
                addform:{
                    id:'',
                    contacts: '',
                    streetname: '',
                    telephone: '',
                    address: ''
                },
            tableData: [],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            addeditVisible: false,
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1,
            labelswidth: '160px',
            labelwidth: '120px',
            options:[]
        }
    },
    created() {
        this.getdata();
        this.getselect()
        // console.log(this.options)
    },
    methods: {
        // 获取数据
        async getdata(){
            const { data } = await this.$axios.get(this.$url+'/GetStreetListApi')
            console.log(data)
            this.tableData = data.filter(item=>{
                item.CREATETIME = item.CREATETIME.replace('T',' ')
                return item
            })
        },
        // 获取下来列表
        async getselect(){
            const { data } = await this.$axios.get(this.$url+'/GetRegionListApi')
            this.options = data.filter(item => {
              console.log(item)
              return item
            })
        },
        // 新增弹出框
        addlistdatadiglog(){
            this.addeditVisible = true
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$axios({
                url: this.$url+'/AddStreetApi',
                // url:'http://111.160.78.62:5575/GarbagePointsTYApi/BasicData/AddStreetApi',
                method: 'get',
                params:{
                    REGION_ID: this.addform.REGION_ID,
                    STREET_NAME: this.addform.streetname,
                    ADDRESS: this.addform.address,
                    CONTACTS: this.addform.contacts,
                    lng: this.addform.LONGITUDE,
                    lat: this.addform.LATITUDE,
                    TELEPHONE: this.addform.telephone
                }
            }).then((res)=>{
                console.log(res)
                if(res.data.IsSucess){
                    this.$message.success('新增成功');
                    if(this.addeditVisible){
                        this.addeditVisible =false
                    }
                    this.addform = Object.assign({},undefined)
                    this.getdata()
                }
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        })
        },
        resetForm(formName) {
        this.$refs[formName].resetFields();
        this.addeditVisible = false
      },
        // 新增
        addsaveEdit(addform){
            // console.log(id)
            // console.log({
            //         REGION_ID: this.addform.REGION_ID,
            //         STREET_NAME: this.addform.streetname,
            //         ADDRESS: this.addform.address,
            //         CONTACTS: this.addform.contacts,
            //         TELEPHONE: this.addform.telephone
            //     })
            // console.log(addform)
            
            // this.getdata()
        },
        // getid(){
        //     this.$axios({
        //         url:this.$url+'/communityListsApi?=id'+this.addform.REGION_ID,
        //         method:'get'
        //     }).then(res=>{
        //         console.log(res)
        //     })
        //     console.log(this.addform.REGION_ID)
        // },
        // 模糊搜索
        mohu() {
            var newdate = [];
            if(this.searchform.name){
                if(this.searchform.name)
                 this.tableData.filter(item=>{
                     console.log(item)
                    if(item.REGION_NAME.indexOf(this.searchform.name) != -1){
                        newdate.push(item)
                    }
                })
            }else if (this.searchform.name == ''){
                this.getdata()
            }
            this.tableData = newdate
        },
         // 文件选择回调
   onChange(file, fileList) {
    //  console.log(fileList);
     this.fileData = file; // 保存当前选择文件
     this.readExcel(); // 调用读取数据的方法
   },
   // 读取数据
   readExcel(e) {
     let that = this;
     const files = that.fileData;
     console.log(files);
     if (!files) {
       //如果没有文件
       return false;
     } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
       this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
       return false;
     }
     const fileReader = new FileReader();
     console.log("data2" +fileReader)
     fileReader.onload = ev => {
       try {
         const data = ev.target.result;
        //  console.log(ev.target)
        //  console.log(this);
         const workbook = this.XLSX.read(data, {
           type: "binary"
         });
         if (workbook.SheetNames.length >= 1) {
        //    this.$message({
        //      message: "导入数据表格成功",
        //      showClose: true,
        //      type: "success"
        //    });
         }
         const wsname = workbook.SheetNames[0]; //取第一张表
         const ws = this.XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
         this.$axios({
           url:this.$url +'/ImportStreetApi' ,
           method:'post',
           data: ws
         }).then(res=>{
             console.log(res)
        //    if(res.data.IsSucess){
        //        this.$message.success('导入成功')
        //    }
         })
         console.log("data3" +ws)
         that.outputs = []; //清空接收数据
         for (var i = 0; i < ws.length; i++) {
           var sheetData = {
             // 键名为绑定 el 表格的关键字，值则是 ws[i][对应表头名]
            //  ID: ws[i]["ID"],
             REGION_NAME: ws[i]["REGION_NAME"],
             STREET_NAME: ws[i]["STREET_NAME"],
             ADDRESS: ws[i]["ADDRESS"],
             CONTACTS: ws[i]["CONTACTS"],
             TELEPHONE: ws[i]["TELEPHONE"],
            //  LOCATION: ws[i]["位置"],
            //  WEIGHT_YH: ws[i]['重量'],
            //  SIZE: ws[i]["类型"],
            //  PHOTO: ws[i]['图片'],
            //  REMARK: ws[i]['备注'],
           };
           that.tableData.unshift(sheetData);
         }
         
         this.$refs.upload.value = "";
       } catch (e) {
         return false;
       }
     };
     // 如果为原生 input 则应是 files[0]
     fileReader.readAsBinaryString(files.raw);
   },
        // 导出功能
        exportToExcel(){
            require.ensure([],()=>{
              const {export_json_to_excel} = require('../../excel/export2Excel');
              const tHeader = ['ID','REGION_NAME','STREET_NAME', 'ADDRESS','CONTACTS','TELEPHONE'];
              const filterVal = ['STREET_ID','REGION_NAME','STREET_NAME', 'ADDRESS','CONTACTS','TELEPHONE'];
              const list = this.tableData;
              const data = this.formatJson(filterVal, list);
              console.log(data)
              export_json_to_excel(tHeader, data, "街道信息列表");
            });
        },
        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]));
        },
        streetnamemohu(){
             var streetname = this.searchform.streetname;
             var newdate = [];
             if(streetname){
                if(streetname)
                 this.tableData.filter(item=>{
                    //  console.log(item)
                    if(item.STREET_NAME.indexOf(streetname) != -1){
                        newdate.push(item)
                    }
                })
            }else if (streetname == ''){
                this.getdata()
            }
            this.tableData = newdate
        },
        searchbtn(searchform){
            this.tableData = this.tableData.filter(item =>{
                if(item.REGION_NAME.search(searchform.name) != -1){
                    this.tableData = item.filter(items =>{
                        if(items.STREET_NAME.search(searchform.streetname) !=-1){
                            console.log(items)
                        }
                    })
                    
                }
            })
            // console.log(searchform)
        },
        handle(){
            this.$router.push('/streetintegral')
        },
        // 编辑操作
        handleEdit(index, row) {
            // console.log(index,row)
            // this.idx = index;
            this.editform = Object.assign({},row)
            // this.editform = row;
            this.editVisible = true;
        },
        handleDelete(index, row) {
            console.log(index,row)
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            }).then(() => {
                this.$axios({
                    url:this.$url+'/DeleteStreetApi',
                    params:{
                        STREET_ID: row.STREET_ID
                    }
                }).then(res=>{
                    this.getdata()
                })
                    this.$message.success('删除成功');
                    
                })
                .catch(() => {});
        },
        // 保存编辑
        saveEdit() {
            let studenteList= this.editform;
            console.log(studenteList)
            this.$axios({
                url: this.$url + '/UpdateStreetApi',
                method: 'get',
                params: {
                    STREET_ID: studenteList.STREET_ID,
                    REGION_ID: studenteList.REGION_ID,
                    STREET_NAME: studenteList.STREET_NAME,
                    ADDRESS: studenteList.ADDRESS,
                    CONTACTS: studenteList.CONTACTS,
                    lng: studenteList.LONGITUDE,
                    lat: studenteList.LATITUDE,
                    TELEPHONE: studenteList.TELEPHONE
                }
            }).then(item =>{
                if(item.data.IsSucess){
                    this.$message.success('编辑成功');
                    this.getdata()
                }
            })
            this.editVisible = false;
            // // this.$axios({
            // //     url:this.$url+'/UpdateStreetApi',
            // //     method: 'get',
            // //     params:{
            // //         REGION_ID: form.REGION_ID,
            // //         STREET_NAME: form.streetname,
            // //         ADDRESS: form.address,
            // //         CONTACTS: form.contacts,
            // //         TELEPHONE: form.telephone
            // //     }
            // // }).then((res)=>{
            // //     if(res.data.IsSucess){
            // //         this.$message.success('新增成功');
            // //         this.getdata()
            // //     }
            // // })
        },
        // 分页导航
        handlePageChange(currentPage) {
            this.currentPage = currentPage;
            console.log(this.currentPage)
            // this.$set(this.query, 'pageIndex', val);
            // this.getData();
        },
        handleSizeChange(size){
            this.pagesize = size;
            console.log(this.pagesize)
        }
    }
}
</script>
<style scoped>
.el-select{
    width: 100%;
}
/deep/.el-upload__input{
    display: none;
}
/deep/.el-upload__input{
    display: none;
}
/deep/.el-form-item__content{
    display: flex;
}
</style>